import React, { useEffect, useState, useRef } from 'react';
import { Table, Card, Tag, Button, Modal, InputNumber, Input, message, Space } from 'antd';

// 获取当前用户角色（从localStorage的user对象获取）
const getCurrentUserRole = () => {
  // 解析localStorage中的user对象，返回role字段，默认为employee
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  return user.role || 'employee';
};

const StockManagement = () => {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [editing, setEditing] = useState(null);
  const [showAddInput, setShowAddInput] = useState(false);
  const [addValue, setAddValue] = useState(0);
  const addInputRef = useRef(null);
  const role = getCurrentUserRole();
  const [editStock, setEditStock] = useState(0); // 管理员编辑库存
  const [editWarning, setEditWarning] = useState(20); // 管理员编辑预警值
  const [showAddStockInput, setShowAddStockInput] = useState(false); // 是否显示增加库存输入框
  const [showRemoveStockInput, setShowRemoveStockInput] = useState(false); // 是否显示减少库存输入框
  const [showEditWarningInput, setShowEditWarningInput] = useState(false); // 是否显示修改预警值输入框

  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      const res = await fetch('http://localhost:3001/api/products');
      const data = await res.json();
      setProducts(data.map(item => ({ ...item, warning: item.warning ?? 20 })));
      setLoading(false);
    };
    fetchProducts();
  }, []);

  useEffect(() => {
    if (showAddInput && addInputRef.current) {
      addInputRef.current.focus();
    }
  }, [showAddInput]);

  const handleEdit = (record) => {
    setEditing(record);
    setShowAddInput(false);
    setAddValue(0);
    setEditStock(record.stock); // 初始化库存
    setEditWarning(record.warning || 20); // 初始化预警值
    setModalVisible(true);
  };

  const handleAddInputFocus = () => {
    if (addValue === 0) setAddValue('');
  };

  const handleOk = async () => {
    if (role === 'admin') {
      // 管理员可直接修改库存和预警值
      if (editStock < 0 || editWarning < 0) {
        message.error('库存和预警值不能为负数');
        return;
      }
      // 并发更新库存和预警值
      const [res1, res2] = await Promise.all([
        fetch(`http://localhost:3001/api/products/${editing._id}/set-stock`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ stock: editStock })
        }),
        fetch(`http://localhost:3001/api/products/${editing._id}/set-warning`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ warning: editWarning })
        })
      ]);
      const data1 = await res1.json();
      const data2 = await res2.json();
      if (data1.success && data2.success) {
        message.success('库存和预警值已更新');
        setModalVisible(false);
        setShowAddInput(false);
        setAddValue(0);
        setShowAddStockInput(false); // 关闭增加库存输入框
        setShowRemoveStockInput(false); // 关闭减少库存输入框
        setShowEditWarningInput(false); // 关闭修改预警值输入框
        // 刷新数据
        const res2 = await fetch('http://localhost:3001/api/products');
        const data2 = await res2.json();
        setProducts(data2.map(item => ({ ...item, warning: item.warning ?? 20 })));
      } else {
        message.error((data1.error || data2.error) || '库存/预警值更新失败');
      }
    } else {
      // 员工只能增加库存
      if (!showAddInput || !addValue || Number(addValue) <= 0) {
        message.error('请输入要增加的库存数量');
        return;
      }
      const newStock = editing.stock + Number(addValue);
      const res = await fetch(`http://localhost:3001/api/products/${editing._id}/set-stock`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ stock: newStock })
      });
      const data = await res.json();
      if (data.success) {
        message.success('库存已更新');
        setModalVisible(false);
        setShowAddInput(false);
        setAddValue(0);
        setShowAddStockInput(false); // 关闭增加库存输入框
        setShowRemoveStockInput(false); // 关闭减少库存输入框
        setShowEditWarningInput(false); // 关闭修改预警值输入框
        // 刷新数据
        const res2 = await fetch('http://localhost:3001/api/products');
        const data2 = await res2.json();
        setProducts(data2.map(item => ({ ...item, warning: item.warning ?? 20 })));
      } else {
        message.error(data.error || '库存更新失败');
      }
    }
  };

  const columns = [
    { title: '商品名称', dataIndex: 'name', key: 'name' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '单价', dataIndex: 'price', key: 'price', render: v => `¥${v}` },
    { title: '库存', dataIndex: 'stock', key: 'stock', render: stock => <Tag color={stock > 0 ? 'blue' : 'red'}>{stock}</Tag> },
    { title: '预警值', dataIndex: 'warning', key: 'warning', render: v => <Tag color="orange">{v}</Tag> },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button size="small" onClick={() => handleEdit(record)}>
          {role === 'admin' ? '调整库存/预警值' : '添加库存'}
        </Button>
      )
    }
  ];

  // 公共卡片样式，和商品管理页面保持一致
  const cardStyle = {
    maxWidth: 1100, // 最大宽度
    margin: '0 auto', // 居中
    boxShadow: '0 4px 24px rgba(99,102,241,0.08)', // 阴影
    borderRadius: 18, // 圆角
    background: '#fff', // 白色背景
    padding: '24px 32px' // 内边距
  };

  return (
    <Card
      title={<span style={{ fontWeight: 700, fontSize: 22, letterSpacing: 1 }}>库存管理</span>}
      style={cardStyle}
      headStyle={{ borderBottom: '1px solid #f0f0f0', background: 'transparent', marginBottom: 16 }}
      bodyStyle={{ padding: 0 }}
    >
      <Table
        columns={columns}
        dataSource={products}
        rowKey="_id"
        loading={loading}
        pagination={{ pageSize: 10 }}
        scroll={{ x: 'max-content' }}
        bordered
      />
      <Modal
        title={role === 'admin' ? '调整库存和预警值' : '添加库存'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={() => {
          setModalVisible(false);
          setShowAddInput(false);
          setAddValue(0);
          setShowAddStockInput(false); // 关闭增加库存输入框
          setShowRemoveStockInput(false); // 关闭减少库存输入框
          setShowEditWarningInput(false); // 关闭修改预警值输入框
        }}
        destroyOnClose
      >
        {editing && (
          <>
            <div style={{ marginBottom: 16 }}>
              <span>当前库存：</span>
              {role === 'admin' ? (
                <>
                  {/* 纯文本显示当前库存，使用editStock以便实时变化 */}
                  <span style={{ fontWeight: 'bold', marginRight: 16 }}>{editStock}</span>
                  {/* 增加库存按钮 */}
                  <Button
                    type="primary"
                    size="small"
                    style={{ marginRight: 8 }}
                    onClick={() => {
                      setShowAddStockInput(!showAddStockInput);
                      setShowRemoveStockInput(false);
                    }}
                  >增加库存</Button>
                  {/* 删除库存按钮 */}
                  <Button
                    danger
                    size="small"
                    onClick={() => {
                      setShowRemoveStockInput(!showRemoveStockInput);
                      setShowAddStockInput(false);
                    }}
                  >减少库存</Button>
                  {/* 增加库存输入框 */}
                  {showAddStockInput && (
                    <div style={{ marginTop: 8 }}>
                      <span>增加数量：</span>
                      <InputNumber
                        min={1}
                        value={addValue}
                        onChange={setAddValue}
                        style={{ width: 120, marginRight: 8 }}
                        controls={false}
                        onFocus={() => { if (addValue === 0) setAddValue(''); }}
                      />
                      <Button
                        type="primary"
                        size="small"
                        onClick={() => {
                          setEditStock(editStock + Number(addValue));
                          setShowAddStockInput(false);
                          setAddValue(0);
                        }}
                      >确认增加</Button>
                    </div>
                  )}
                  {/* 删除库存输入框 */}
                  {showRemoveStockInput && (
                    <div style={{ marginTop: 8 }}>
                      <span>减少数量：</span>
                      <InputNumber
                        min={1}
                        max={editStock}
                        value={addValue}
                        onChange={setAddValue}
                        style={{ width: 120, marginRight: 8 }}
                        controls={false}
                        onFocus={() => { if (addValue === 0) setAddValue(''); }}
                      />
                      <Button
                        danger
                        size="small"
                        onClick={() => {
                          setEditStock(editStock - Number(addValue));
                          setShowRemoveStockInput(false);
                          setAddValue(0);
                        }}
                      >确认减少</Button>
                    </div>
                  )}
                </>
              ) : (
                <span style={{ fontWeight: 'bold', marginRight: 16 }}>{editing.stock}</span>
              )}
              {/* 只有员工可以添加库存 */}
              {role !== 'admin' && (
                <Button type="primary" onClick={() => setShowAddInput(true)} disabled={showAddInput}>
                  添加库存
                </Button>
              )}
            </div>
            {/* 只有员工可见的添加库存输入框 */}
            {showAddInput && role !== 'admin' && (
              <Space style={{ marginBottom: 16 }}>
                <span>增加数量：</span>
                <InputNumber
                  min={1}
                  value={addValue}
                  onChange={setAddValue}
                  controls={false}
                  style={{ width: 120 }}
                  ref={addInputRef}
                  onFocus={handleAddInputFocus}
                />
              </Space>
            )}
            <div style={{ marginTop: 16 }}>
              <span>预警值：</span>
              {role === 'admin' ? (
                <>
                  {/* 纯文本显示预警值 */}
                  <span style={{ fontWeight: 'bold', marginRight: 16 }}>{editWarning}</span>
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => setShowEditWarningInput(!showEditWarningInput)}
                  >修改预警值</Button>
                  {/* 修改预警值输入框 */}
                  {showEditWarningInput && (
                    <div style={{ marginTop: 8 }}>
                      <InputNumber
                        min={0}
                        value={editWarning}
                        onChange={setEditWarning}
                        style={{ width: 120, marginRight: 8 }}
                        controls={false}
                        onFocus={e => { if (editWarning === 0) setEditWarning(''); }}
                      />
                      <Button
                        type="primary"
                        size="small"
                        onClick={async () => {
                          // 调用后端接口更新预警值
                          const res = await fetch(`http://localhost:3001/api/products/${editing._id}/set-warning`, {
                            method: 'PUT',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ warning: editWarning })
                          });
                          const data = await res.json();
                          if (data.success) {
                            message.success('预警值已更新');
                            setShowEditWarningInput(false); // 关闭输入框
                            // 刷新商品数据
                            const res2 = await fetch('http://localhost:3001/api/products');
                            const data2 = await res2.json();
                            setProducts(data2.map(item => ({ ...item, warning: item.warning ?? 20 })));
                          } else {
                            message.error(data.error || '预警值更新失败');
                          }
                        }}
                      >确认</Button>
                    </div>
                  )}
                </>
              ) : (
                <span style={{ fontWeight: 'bold' }}>{editing.warning}</span> // 员工看到真实预警值
              )}
            </div>
          </>
        )}
      </Modal>
    </Card>
  );
};

export default StockManagement; 